import { ref, onMounted, onUnmounted, type Ref } from "vue";

interface Viewport {
  left: number;
  right: number;
  top: number;
  bottom: number;
}

interface Point {
  id: number;
  lat: number;
  lng: number;
  speed: number;
  direction: number;
  timestamp: number;
}

export function useDataProcessor() {
  const worker: Ref<Worker | null> = ref(null);
  const processedData: Ref<Point[]> = ref([]);
  const isProcessing: Ref<boolean> = ref(false);
  const error: Ref<Error | null> = ref(null);

  // 初始化Worker
  onMounted(() => {
    try {
      worker.value = new Worker(
        new URL("../workers/dataProcessor.worker.js", import.meta.url)
      );

      worker.value.onmessage = (e: MessageEvent) => {
        processedData.value = e.data;
        isProcessing.value = false;
      };

      worker.value.onerror = (err: ErrorEvent) => {
        error.value = new Error(`Worker error: ${err.message}`);
        isProcessing.value = false;
      };
    } catch (err) {
      error.value = err as Error;
    }
  });

  // 销毁Worker
  onUnmounted(() => {
    if (worker.value) {
      worker.value.terminate();
      worker.value = null;
    }
  });

  // 处理数据方法
  const processData = (data: Point[], viewport: Viewport) => {
    if (!worker.value || isProcessing.value) return;

    isProcessing.value = true;
    worker.value.postMessage({
      type: "process",
      data,
      viewport
    });
  };

  return {
    processedData,
    isProcessing,
    error,
    processData
  };
}
